package xx.netty.start;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * netty 服务端
 */
public class HelloNettyServer {

    public static void main(String[] args) {
        // 1. 启动器，负责组装netty组件并启动服务器
        new ServerBootstrap()
                //  2.BossEventLoop, WorkerEventLoop(selector, thread)
                .group(new NioEventLoopGroup())
                // 3. 选择服务器的 ServerSocketChannel 实现
                .channel(NioServerSocketChannel.class)
                //  4. 配置 worker(child) 能执行的操作 handler
                .childHandler(
                        // 5. channel 初始化，负责添加别的 handler
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                                // 6. 添加具体的 handler
                                // StringDecoder 具体的消息解码器，将字节流转换成字符串
                                nioSocketChannel.pipeline().addLast(new StringDecoder());
                                // 自定义的消息处理器，当有消息到达时，将其打印出来
                                nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg){
                                        System.out.println(msg);
                                    }
                                });
                            }
                        }
                )
                // 7. 绑定监听端口
                .bind(1001);
        System.out.println(" abc ");
        System.out.println(" abc ".trim());
        System.out.println(" abc".trim());
        System.out.println("abc ".trim());
    }
}
